package com.zjh.document.controller;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjh.admin.service.SysConfigService;
import com.zjh.common.entity.Response;
import com.zjh.common.entity.ResponseCode;
import com.zjh.common.exception.ServiceException;
import com.zjh.document.entity.DTO.FileObject;
import com.zjh.document.entity.QTO.SystemFIleQto1;
import com.zjh.document.service.impl.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/documentManager/fileBrowser/files")
public class FileController {

    private final FileService fileService;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SysConfigService sysConfigService;

    @Value("${document.local.url}")
    private String localFileUrl;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping("getAllfileByFolder")
    public Response<List<FileObject>> listFiles(@RequestParam(required = false) String path) {
        try {
            List<FileObject> files = fileService.listFiles(path);
            return Response.success(files);
        } catch (IOException e) {
            return Response.error("查询文件列表失败: " + path);
        }
    }

    @PostMapping("/upload")
    public Response<?> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "path", required = false) String path) {
        try {
            String res = fileService.storeFile(fileName, path, file);

            return Response.success(fileName + "保存成功: " + res);

        } catch (Exception e) {
            return Response.error(e.getMessage());
        }
    }

    @GetMapping("/getLocalFileUrl")
    public Response<String> getLocalFileUrl(@RequestParam(value = "fileName", required = false) String fileName,
                                            @RequestParam(value = "path", required = false) String path) {

        if (!path.endsWith("/")) {
            path = path + "/";
        }

        String fileUrl = localFileUrl + path + fileName;

        return Response.success(fileUrl);
    }

    @GetMapping("/download")
    public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {
        try {
            Path _path = Paths.get(filePath);
            File file = _path.toFile();

            InputStream fileInputStream = fileService.downloadFile(file);

            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            String contextType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            response.setContentType(contextType);
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());

        } catch (IOException e) {
            log.error("下载失败");
        }
    }

    @PostMapping("/moveFile")
    public Response<?> moveFile(@RequestBody SystemFIleQto1 qto1) {
        boolean b = fileService.moveFile(qto1.getSourceFilePath(), qto1.getTargetFolderPath());
        if (b) {
            return Response.success();
        } else {
            return Response.error("移动文件失败");
        }

    }

    @PostMapping("/moveFolder")
    public Response<?> moveFolder(@RequestBody SystemFIleQto1 qto1) {
        boolean b = fileService.moveFolder(qto1.getSourceFilePath(), qto1.getTargetFolderPath());
        if (b) {
            return Response.success();
        } else {
            return Response.error("移动文件夹失败");
        }

    }

    @GetMapping("/preview")
    public void previewDrawioFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {
        try {
            Path path = Paths.get(filePath);
            File file = path.toFile();
            InputStream inputStream = new FileInputStream(file);

            response.setContentType("application/xml"); // 非 attachment
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            log.error("读取失败", e);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @GetMapping("/getText")
    public Response<String> getText(@RequestParam String fileName) throws Exception {

        String res = fileService.readTextFile(fileName);

        return Response.success(res);
    }

    /**
     * 新建文件夹
     */
    @PostMapping("/newFolder")
    public Response<?> newFolder(@RequestParam("currentPath") String currentPath, @RequestParam("folderName") String folderName) {
        String path = null;
        if (StringUtils.isBlank(currentPath)) {

            String systemConfig = sysConfigService.getConfigByConfigName("systemConfig");
            Map<String, Object> configMap = null;
            try {
                configMap = objectMapper.readValue(JSON.parse(systemConfig).toString(), Map.class);
            } catch (JsonProcessingException e) {
                throw new ServiceException(e);
            }
            String rootPath = (String) configMap.get("localFileStoragePath");

            path = rootPath + folderName;
        } else {
            path = currentPath + "/" + folderName;
        }

        boolean b = fileService.newFolder(path);
        if (b) {
            return Response.success();
        }
        return Response.error("创建失败");

    }

    /**
     * 新建文件
     */
    @PostMapping("/newFile")
    public Response<?> newFile(@RequestParam("currentPath") String currentPath, @RequestParam("fileName") String fileName) {
        String path = null;

        String systemConfig = sysConfigService.getConfigByConfigName("systemConfig");
        Map<String, Object> configMap = null;
        try {
            configMap = objectMapper.readValue(JSON.parse(systemConfig).toString(), Map.class);
        } catch (JsonProcessingException e) {
            throw new ServiceException(e);
        }
        String rootPath = (String) configMap.get("localFileStoragePath");

        if (StringUtils.isBlank(currentPath)) {
            path = rootPath + fileName;
        } else {
            path = currentPath + "/" + fileName;
        }
        log.info("创建文件： " + path);

        boolean b = fileService.newFile(path);
        if (b) {
            return Response.success("创建成功");
        }
        return Response.error("创建失败");

    }

    /**
     * 删除文件夹
     */
    @PostMapping("/deleteFolder")
    public Response<?> deleteFolder(@RequestParam("path") String path) {
        boolean b = fileService.deleteFolder(path);
        if (b) {
            return Response.success();
        } else {
            return Response.error();
        }
    }

    /**
     * 删除文件
     */
    @PostMapping("/deleteFile")
    public Response deleteFile(@RequestParam("filePath") String filePath) {
        boolean b = fileService.deleteFile(filePath);
        if (b) {
            return Response.success();
        } else {
            return Response.error();
        }
    }

    /**
     * 重命名文件
     */
    @PostMapping("/rename-file")
    public Response<?> renameFile(
            @RequestParam String path,
            @RequestParam String newName) {
        try {
            boolean success = fileService.renameFile(path, newName);
            return Response.success(success);
        } catch (FileNotFoundException e) {
            return Response.error(ResponseCode.NOT_FOUND, e.getMessage());
        } catch (IOException e) {
            return Response.error(ResponseCode.FAILED, e.getMessage());
        }
    }

    /**
     * 重命名文件夹
     */
    @PostMapping("/rename-directory")
    public Response<?> renameDirectory(
            @RequestParam String path,
            @RequestParam String newName) {
        try {
            boolean success = fileService.renameDirectory(path, newName);
            return Response.success(success);
        } catch (FileNotFoundException e) {
            return Response.error(e.getMessage());
        } catch (IOException e) {
            return Response.error(e.getMessage());
        }
    }
}